<template>
  <grid :title="id === 'add' ? '新建文章' : '编辑文章'">
    <el-form ref="form"
             style="text-align: left; width:1000px"
             label-width="100px"
             @submit.native.prevent
             :model="form"
             :rules="rules">
      <el-form-item label="标题"
                    prop="title">
        <el-input v-model="form.title"
                  placeholder="请输入标题，限120个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="简介"
                    prop="summary">
        <el-input v-model="form.summary"
                  type="textarea"
                  placeholder="请输入简介，限300个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="关键词"
                    prop="keywords">
        <el-tag v-for="(tag,index) in form.keywords"
                :key="index"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <template v-if="inputVisible">
          <el-input class="input-new-tag"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @blur="handleInputConfirm">
          </el-input>
        </template>
        <template v-else>
          <el-button class="button-new-tag"
                     size="small"
                     @click="showInput">+ New</el-button>
        </template>
      </el-form-item>
      <el-form-item label="分类"
                    prop="cate_id">
        <el-select v-model="form.cate_id">
          <el-option v-for="item in cates"
                     :label="item.name"
                     :value="item.id"
                     :key="item.id"></el-option>
        </el-select>
        <el-tag type="success"
                size="medium"
                style="cursor: pointer;margin-left:10px;"
                @click="showDialog('cate')">新增分类</el-tag>
      </el-form-item>
      <el-form-item label="标签"
                    prop="tag_list">
        <el-select multiple
                   v-model="form.tag_list">
          <el-option v-for="item in tags"
                     :label="item.name"
                     :value="item.id"
                     :key="item.id"></el-option>
        </el-select>
        <el-tag type="success"
                size="medium"
                style="cursor: pointer;margin-left:10px;"
                @click="showDialog('tag')">新增标签</el-tag>
      </el-form-item>
      <el-form-item label="封面图"
                    prop="image">
        <image-input type="item"
                     v-model="form.image"></image-input>
        <p class="caption">注：建议上传尺寸60*60的 PNG图</p>
      </el-form-item>

      <el-form-item label="显示">
        <el-checkbox v-model="form.status"
                     :true-label="1"
                     :false-label="0">开启</el-checkbox>
        <p class="caption">关闭后文章将不会被查看与搜索</p>
      </el-form-item>
      <el-form-item label="精选">
        <el-checkbox v-model="form.chosen"
                     :true-label="1"
                     :false-label="0">开启</el-checkbox>
        <p class="caption">开启后文章将进行上浮操作</p>
      </el-form-item>
      <el-form-item label="评论">
        <el-checkbox v-model="form.allow_comment"
                     :true-label="1"
                     :false-label="0">开启</el-checkbox>
        <p class="caption">关闭时该文章将不允许被评论</p>
      </el-form-item>
      <el-form-item label="是否转载">
        <el-checkbox v-model="form.copyright"
                     :true-label="1"
                     :false-label="0">开启</el-checkbox>
        <p class="caption">转载文章需要设置原链接</p>
      </el-form-item>
      <template v-if="form.copyright === 1">
        <el-form-item label="转载网站名称"
                      prop="original_website">
          <el-input v-model="form.original_website"
                    placeholder="请输入转载网站名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="转载链接"
                      prop="original_link">
          <el-input v-model="form.original_link"
                    placeholder="请输入转载地址"
                    clearable></el-input>
        </el-form-item>
      </template>
      <el-form-item label="内容"
                    prop="content">
        <el-tabs type="border-card"
                 v-model="checkTabName"
                 @tab-click="checkContentTag">
          <el-tab-pane label="MarkDown"
                       name="mark-down">
            <markdown-editor v-if="
                       form.type==1"
                             v-model="form.content">
            </markdown-editor>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="onFormSubmit">保存</el-button>
        <router-link :to="{ name: 'topic'}">
          <el-button>取消</el-button>
        </router-link>
      </el-form-item>
    </el-form>

    <el-dialog title="新增分类"
               :visible.sync="dialogCateVisible"
               width="650px"
               :show-close="false"
               center>
      <el-form ref="dialogCateForm"
               :model="cateForm"
               label-width="120px"
               :rules="dialogRules">
        <el-form-item label="名称"
                      prop="name">
          <el-input v-model="cateForm.name"
                    autocomplete="off"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="cateForm.status"
                     active-text="显示"
                     :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogCateVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="onDialogSubmit('cate')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增标签"
               :visible.sync="dialogTagVisible"
               width="650px"
               :show-close="false"
               center>
      <el-form ref="dialogTagForm"
               :model="tagForm"
               label-width="120px"
               :rules="dialogRules">
        <el-form-item label="名称"
                      prop="name">
          <el-input v-model="tagForm.name"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="tagForm.status"
                     active-text="显示"
                     :active-value="1"
                     :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogTagVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="onDialogSubmit('tag')">确 定</el-button>
      </div>
    </el-dialog>
  </grid>
</template>

<script>
import { fetchList as fetchCates, store as cateStore } from '@/views/cate/api'
import { fetchList as fetchTags, store as tagStore } from '@/views/tag/api'
import imageInput from '@/components/image-input'
import markdownEditor from '@/components/mark-down-editor'
import { store, edit, fetchView } from './api'

export default {
  title () {
    return this.id === 'add' ? '新增文章' : '编辑文章'
  },
  props: {
    id: {
      type: String,
      default: 'add'
    }
  },
  data () {
    const validateLink = (rule, value, callback) => {
      if (this.form.copyright === 1 && (value === '' || value === undefined)) {
        callback(new Error('请输入转载信息'))
      } else {
        callback()
      }
    }
    return {
      inputVisible: false,
      inputValue: '',
      form: {},
      formDefault: {
        title: undefined,
        summary: undefined,
        keywords: [],
        cate_id: undefined,
        tag_list: undefined,
        type: 1,
        image: [],
        content: '',
        status: 1,
        allow_comment: 1,
        chosen: 0,
        copyright: 0,
        original_website: undefined,
        original_link: undefined
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空' },
          { max: 120, message: '最长120个字' }
        ],
        summary: [
          { required: true, max: 300, message: '最长300个字' }
        ],
        cate_id: [
          { required: true, message: '分类不能为空' }
        ],
        tag_list: [
          { required: true, message: '标签不能为空' }
        ],
        content: [
          { required: true, message: '内容不能为空' }
        ],
        original_website: [
          { validator: validateLink }
        ],
        original_link: [
          { validator: validateLink }
        ]
      },
      cates: [],
      tags: [],
      editorOption: {
        // something config
      },
      checkTabName: 'mark-down',
      dialogTagVisible: false,
      dialogCateVisible: false,
      cateForm: {
        id: undefined,
        name: undefined,
        status: 1
      },
      tagForm: {
        id: undefined,
        name: undefined,
        status: 1
      },
      dialogRules: {
        name: [
          { required: true, message: '名称不能为空' }
        ]
      }
    }
  },
  components: {
    imageInput, markdownEditor
  },
  async mounted () {
    this.fecthCateList()
    this.fecthTagList()
    if (this.id !== 'add') {
      const {
        data: { data }
      } = await fetchView(this.id)
      this.form = await this.filterTopic(data)
    } else {
      this.form = this.formDefault
    }
  },
  methods: {
    handleClose (tag) {
      this.form.keywords.splice(this.form.keywords.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      if (this.inputValue) {
        this.form.keywords.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    async filterTopic (data) {
      let form = {}
      for (let [key, value] of Object.entries(this.formDefault)) {
        form[key] = data[key] || value
      }
      form.image = (form.image && form.image.url) ? [form.image] : []
      if (data.tag_list.length) {
        form.tag_list = data.tag_list.map((value, index, array) => {
          return value.id
        })
      }
      return form
    },
    async fecthCateList () {
      await fetchCates({ limit: 50 }).then(({ data: { data } }) => {
        this.cates = data
      })
    },
    async fecthTagList () {
      await fetchTags({ limit: 50 }).then(({ data: { data } }) => {
        this.tags = data
      })
    },
    checkContentTag (type) {
      if (type.name === 'mark-down') {
        this.form.type = 1
      } else {
        this.form.type = 2
      }
    },
    async onFormSubmit () {
      await this.$refs.form.validate()
      let params
      if (this.form.image.length) {
        const {
          image: [{ id, url }],
          ...r
        } = this.form
        params = { ...r, image: { id, url } }
      } else {
        const { image, ...r } = this.form
        params = { ...r, image: {} }
      }
      if (this.id === 'add') {
        await store(params)
      } else {
        await edit(this.id, params)
      }
      this.$message.success('保存成功')
      this.$router.back()
    },
    showDialog (type) {
      if (type === 'cate') {
        this.dialogCateVisible = true
        this.$nextTick(() => this.$refs.dialogCateForm.clearValidate())
      } else {
        this.dialogTagVisible = true
        this.$nextTick(() => this.$refs.dialogTagForm.clearValidate())
      }
    },
    async onDialogSubmit (type) {
      if (type === 'cate') {
        await this.$refs.dialogCateForm.validate()
        const { data: { data } } = await cateStore(this.cateForm)
        await this.fecthCateList()
        this.form.cate_id = data.id
        this.dialogCateVisible = false
      } else {
        await this.$refs.dialogTagForm.validate()
        const { data: { data } } = await tagStore(this.tagForm)
        await this.fecthTagList()
        if (this.tag_list === undefined) {
          this.form.tag_list = [data.id]
        } else {
          this.form.tag_list.push(data.id)
        }
        this.dialogTagVisible = false
      }
      this.$message.success('保存成功')
    }
  }
}
</script>
